package com.itqf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itqf.bean.*;
import com.itqf.dto.CommonsDto;
import com.itqf.mapper.DtsGoodsMapper;
import com.itqf.service.*;
import com.itqf.util.ResponseUtil;
import com.itqf.utils.AdminResponseCode;
import com.itqf.utils.AdminResponseUtil;
import com.itqf.vo.CatVo;
import com.itqf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * projectName: gp_manage
 *
 * @author: 赵伟风
 * time: 2021/8/18 17:28
 * description:
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    private DtsGoodsMapper dtsGoodsMapper;

    @Autowired
    private DtsRoleService dtsRoleService;

    @Autowired
    private DtsBrandService dtsBrandService;


    @Autowired
    private DtsGoodsProductService dtsGoodsProductService;

    @Autowired
    private DtsGoodsSpecificationService dtsGoodsSpecificationService;

    @Autowired
    private DtsGoodsAttributeService dtsGoodsAttributeService;

    @Autowired
    private DtsCategoryService dtsCategoryService;


    @Autowired
    private DtsCartService dtsCartService;

    @Autowired
    private DtsOrderGoodsService dtsOrderGoodsService;

    /**
     * 查询商品数量，查询全部
     *
     * @return
     */
    @Override
    public Long findGoodsTotal() {

        //上架  没有逻辑删除
        DtsGoodsExample dtsGoodsExample =  new DtsGoodsExample();
        DtsGoodsExample.Criteria criteria = dtsGoodsExample.createCriteria();

        criteria.andIsOnSaleEqualTo(true);
        criteria.andDeletedEqualTo(false);

        long goodsTotal = dtsGoodsMapper.countByExample(dtsGoodsExample);

        return goodsTotal;
    }

    /**
     * 查询品牌的商品数量
     *
     * @param brandIds
     * @return
     */
    @Override
    public Long findGoodsTotal(List<Integer> brandIds) {

        //上架  没有逻辑删除  品牌
        DtsGoodsExample dtsGoodsExample =  new DtsGoodsExample();
        DtsGoodsExample.Criteria criteria = dtsGoodsExample.createCriteria();

        criteria.andIsOnSaleEqualTo(true);
        criteria.andDeletedEqualTo(false);
        criteria.andBrandIdIn(brandIds);

        long goodsTotal = dtsGoodsMapper.countByExample(dtsGoodsExample);

        return goodsTotal;
    }



    /**
     * 查询商品信息
     *
     * @param dto
     * @param dtsAdmin
     * @return
     */
    @Override
    public Object findGoodsByPage(CommonsDto dto, DtsAdmin dtsAdmin) {

        //1.判断是不是超级管理员
        boolean  isSuper = dtsRoleService.checkSuper(dtsAdmin.getRoleIds());

        //2.是 查询全部
        //3.不是 查询对应的品牌
        List<Integer> brandIds = null;

        if (!isSuper){
           brandIds =  dtsBrandService.findBrandIdsByAdminId(dtsAdmin.getId());
        }

        Map<String,Object> data = new HashMap<>();

        //没有品牌,并且不是超级管理员
        if ((brandIds == null || brandIds.size() == 0 ) && !isSuper){
            data.put("items", null);
            data.put("total", 0L);

            return data;
        }

        //1.分页
        PageHelper.startPage(dto.getPage(), dto.getLimit());
        //2.条件查询

        DtsGoodsExample goodsExample = new DtsGoodsExample();
        DtsGoodsExample.Criteria criteria = goodsExample.createCriteria();

        if (brandIds != null && brandIds.size() >0){
            criteria.andBrandIdIn(brandIds);
        }

        if (dto.getName() != null) {
            criteria.andNameLike("%"+dto.getName()+"%");
        }

        if (dto.getGoodsSn() != null) {
            criteria.andGoodsSnLike("%"+dto.getGoodsSn()+"%");
        }


        criteria.andDeletedEqualTo(false);

        List<DtsGoods> goods = dtsGoodsMapper.selectByExample(goodsExample);

        //3.pageInfo封装
        PageInfo<DtsGoods> pageInfo = new PageInfo<>(goods);

        //4.结果封装
        data.put("total", pageInfo.getTotal());
        data.put("items", pageInfo.getList());


        return data;
    }

    /**
     * 查询商品详情
     *
     * @param id
     * @return
     */
    @Override
    public Object findGoodsDetailByPrimaryKey(Integer id) {

        //1.根据获取id查询货物信息
        DtsGoods dtsGoods = dtsGoodsMapper.selectByPrimaryKey(id);
        //2.查询库存
        List<DtsGoodsProduct>  dtsGoodsProducts = dtsGoodsProductService.findProductByGid(id);
        //3.查询规格
        List<DtsGoodsSpecification> dtsGoodsSpecifications = dtsGoodsSpecificationService.findSpecificationByGid(id);
        //4.查询参数
        List<DtsGoodsAttribute> goodsAttributes = dtsGoodsAttributeService.findAttributeByGid(id);
        //5.封装类别

        DtsCategory dtsCategory = dtsCategoryService.findCategoryById(dtsGoods.getCategoryId());

        Integer [] categoryIds = new Integer[]{dtsCategory.getPid(),dtsCategory.getId()};

        //6.数据封装

        Map<String, Object> data = new HashMap<>();
        data.put("goods", dtsGoods);
        data.put("specifications", dtsGoodsSpecifications);
        data.put("products", dtsGoodsProducts);
        data.put("attributes", goodsAttributes);
        data.put("categoryIds", categoryIds);

        return data;
    }

    /**
     * 查询品牌和类别数据
     *
     * @param currentUser
     * @return
     */
    @Override
    public Object findCatAndBrand(DtsAdmin currentUser) {

        List<CatVo> categoryList =
                dtsGoodsMapper.queryCats();

        List<Map<String,Object>> brandList =
                dtsGoodsMapper.queryBrands();

        Map<String,Object> data  = new HashMap<>();

        data.put("categoryList",categoryList);
        data.put("brandList",brandList);

        return data;
    }

    /**
     * 更新商品
     *
     * @param goodsAllinone
     * @return
     */
    @Override
    public Object updateGoodsById(GoodsAllinone goodsAllinone) {
        DtsGoods goods = goodsAllinone.getGoods();
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        DtsGoodsProduct[] products = goodsAllinone.getProducts();

        Integer id = goods.getId();
        // 检查是否存在购物车商品或者订单商品
        // 如果存在则拒绝修改商品。
        if (dtsOrderGoodsService.checkExist(id) || dtsCartService.checkExist(id)) {

            return AdminResponseUtil.fail(AdminResponseCode.GOODS_UPDATE_NOT_ALLOWED);
        }


        // 商品基本信息表Dts_goods
        if (dtsGoodsMapper.updateByPrimaryKeySelective(goods) == 0) {
            //logger.error("商品管理->商品管理->编辑错误:{}", "更新数据失败");
            throw new RuntimeException("更新数据失败");
        }

        Integer gid = goods.getId();


        dtsGoodsSpecificationService.deleteByGid(gid);
        dtsGoodsAttributeService.deleteByGid(gid);
        dtsGoodsProductService.deleteByGid(gid);

        // 商品规格表Dts_goods_specification
        for (DtsGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            dtsGoodsSpecificationService.add(specification);
        }

        // 商品参数表Dts_goods_attribute
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            dtsGoodsAttributeService.add(attribute);
        }

        // 商品货品表Dts_product
        for (DtsGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            dtsGoodsProductService.add(product);
        }
        //qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        return ResponseUtil.ok();
    }

    /**
     * 删除商品
     *
     * @param goods
     * @return
     */
    @Override
    public Object deleteGoodsById(DtsGoods goods) {
        Integer id = goods.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }

        Integer gid = goods.getId();
        dtsGoodsMapper.deleteByPrimaryKey(gid);
        dtsGoodsSpecificationService.deleteByGid(gid);
        dtsGoodsAttributeService.deleteByGid(gid);
        dtsGoodsProductService.deleteByGid(gid);

        //logger.info("【请求结束】商品管理->商品管理->删除,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }
}
